import {
  useUserCheckLoginStatusApi,
  useUserGetExpApi,
} from '@/api/user'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const user = ref({
    id: -1,
    username: '',
    email: '',
    exp: -1,
    createTime: '',
    updateTime: '',
    deleted: -1,
    role: '',
    topic: null,
    age: 0,
  })
  const isLogin = ref(false)

  function checkLoginStatus() {
    useUserGetExpApi()
    useUserCheckLoginStatusApi()
      .then((res) => {
        isLogin.value = true
        user.value = res.data.data
      })
      .catch(() => {
        logout()
      })
  }

  const logout = () => {
    user.value = {
      id: -1,
      username: '',
      email: '',
      exp: -1,
      createTime: '',
      updateTime: '',
      deleted: -1,
      role: '',
      topic: null,
      age: 0,
    }
    isLogin.value = false
  }

  // 直接调用 checkLoginStatus 方法
  checkLoginStatus()

  return {
    user,
    isLogin,
    checkLoginStatus,
    logout,
  }
})
